<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>三级联动列表</title>
  </head>
  <body>
    <div>
      <label for="">
        <span>省：</span>
        <select name="" id="provinces">
          <option>请选择省/直辖市</option>
        </select>
      </label>
      <label for="">
        <span> 市：</span>
        <select name="" id="citys">
          <option>请选择省会</option>
        </select>
      </label>
      <label for="">
        <span>区：</span>
        <select name="" id="areas">
          <option>请选择区</option>
        </select>
      </label>
    </div>
    <script src="cities.js"></script>
    <script>
      //  var data = [{
      // "code" : "110000",
      // "name" : "北京市",
      // "children" : [{
      //         "code" : "110100",
      //         "name" : "市辖区",
      //         "children" : [{
      //                 "code" : "110101",
      //                 "name" : "东城区"
      //             },

      //   渲染省下拉------------------------------------------
      // 省
      var provinces = document.querySelector("#provinces");
      for (var i = 0; i < data.length; i++) {
        // 创建省下拉项
        var provinOption = document.createElement("option");
        // data第一层的name为省
        provinOption.text = data[i].name;
        //给每个下拉项value加个索引
        provinOption.value = i;
        // 添加
        provinces.add(provinOption);
      }

      //   渲染市下拉------------------------------------------
      // 市
      var citys = document.querySelector("#citys");
      //   当省的下拉表单元素值发生变化时
      provinces.addEventListener("change", function () {
        // 每次点击变化省时  先清空上次的市列表
        citys.length = 0;
        // 拿到当前选中的value
        var PIndex = provinces.value;
        // 获取到包含市级信息的children数组
        var citysChildren = data[PIndex].children;
        for (var i = 0; i < citysChildren.length; i++) {
          // 创建市下拉项
          var cityOption = document.createElement("option");
          //给每个下拉项value加个索引
          cityOption.value = i;
          //   拿到点击的市级信息
          cityOption.text = citysChildren[i].name;
          citys.add(cityOption);
        }
      });

      //   渲染区下拉------------------------------------------
      // 区
      var areas = document.querySelector("#areas");
      citys.addEventListener("change", function () {
        areas.length = 0;
        var PIndex = provinces.value;
        var CIndex = citys.value;
        // 获取到包含区级信息的children数组
        var areasChildren = data[PIndex].children[CIndex].children;
        for (var i = 0; i < areasChildren.length; i++) {
          var areasOption = document.createElement("option");
          areasOption.text = areasChildren[i].name;
          areas.add(areasOption);
        }
      });
    </script>
  </body>
</html>
